<?php
class Model_Link extends Ac_Model {
    
    
    protected static $_collection = 'link';

    public function __construct($data = array(), $config = array())
    {
        $config['collection'] = 'link';
        parent::__construct($data, $config);
    }
    
    public function __get($name) 
    {
        if ($name == 'listing') {
            return Model_Listing::find($this->ls);
        } else {
            return parent::__get($name);
        }
    }
    
    public static function getTrackingLink($url) 
    {
        $view = Zend_Registry::get('Zend_View');
        
        $res = $view->getUrl('track', 'index', null, null, array('t'=>'l', 'u' => Ac_Util::shorten($url, true)));
        return $res;
    }
    
    public static function track($url)
    {
        $obj = new self;
        
        $obj->url = $url;
        $obj->c_dt = new MongoDate();
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            $obj->hua = $_SERVER['HTTP_USER_AGENT'];
        }
        
        $user_id = '';
        $uniqid  = '';
        
        //get userid
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user_id = Zend_Registry::get('loggedin_user')->_id; 
            $obj->uid = $user_id;
            if (!empty($_COOKIE['ac_bookmark'])) {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
        } else {
            //generate a unique id and put it in a cookie if it doesn 't exists
            if (!empty($_COOKIE['ac_bookmark'])) {
                $uniqid = $_COOKIE['ac_bookmark'];
            }
        }
        
        $obj->cuid = $uniqid;
        $obj->save();
    }
}